<template>
  <div>
    <van-uploader
      class="w-[80px] h-[80px] my-2"
      style="display: block !important"
      v-model="fileList"
      :max-count="1"
      :after-read="afterRead"
    >
      <template #preview-cover="{ file }">
        <div class="preview-cover van-ellipsis">
          {{ file.name }}
        </div>
      </template>
      <div
        class="w-[80px] h-[80px] flex items-center justify-center bg-[#0f212e] rounded border-2 border-[#2f4553] hover:border-[#557086]"
      >
        <van-icon name="plus" />
      </div>
    </van-uploader>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseURL from "@/utils/baseURL.js";
import axios from "axios";

const fileList = ref([]);
const imgUrl = ref("");
const emit = defineEmits(["setImgUrl"]);
// 上传文件
const afterRead = file => {
  // 此时可以自行将文件上传至服务器
  const formData = new FormData();
  // 将文件添加到FormData对象中
  formData.append("file", file.file);
  axios
    .post(`${baseURL}common/upload-picture`, formData, "multipart/form-data")
    .then(res => {
      if (res.data.errno == 0) {
        imgUrl.value = res.data.data.file_url;
        emit("setImgUrl", imgUrl.value);
      }
    });
};
</script>

<style lang="scss" scoped>
.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
</style>
